package com.hsxc.cdz.controller.appController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.base.bean.MyUser;
import com.hsxc.cdz.base.bean.Pile;
import com.hsxc.cdz.base.bean.Station;
import com.hsxc.cdz.base.util.GetRandnum;
import com.hsxc.cdz.base.util.TimeFormatter;
import com.hsxc.cdz.mgmt.pile.PileManager;
import com.hsxc.cdz.mgmt.station.StationManager;

import net.sf.json.JSONObject;

@Controller("shareController")
@RequestMapping("/app")
public class ShareController {

    private static final int SUCCESS = 0; // 请求成功
    private static final int ERR_DATA = 1; // 参数错误
    private static final int ERR_DEVICE = 2; // 设备信息有误
    private static final int FAILURE = 3; // 处理失败

    @Autowired
    private PileManager pileRegister;
    @Autowired
    StationManager stationmanager;

    Logger logger = LoggerFactory.getLogger(ShareController.class);

    // 参数 桩编号（16位验证）\实际地址、桩的账户密码（都是8位数字），
    @RequestMapping(value = "/sharestation", method = RequestMethod.POST)
    @ResponseBody
    public Object sharePile(@RequestBody String json) {
        JSONObject result = new JSONObject();
        Pile newPile = new Pile();
        Station station = new Station();
        result.put("success", true);
        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(json);
            Subject AppUser = SecurityUtils.getSubject();
            String pileNo = jsonObject.getString("pileno");
            String stationNo = GetRandnum.genRandomNum(20);
            if (AppUser == null || AppUser.getPrincipal() == null) {
                result.put("added", false);
                result.put("errcode", MyUser.NO_LOGIN);
                result.put("message", "没有登录");
                return result;
            }
            String userNo = AppUser.getPrincipal().toString();

            if (checkPileNo(pileNo)) {
                newPile.setAccount(jsonObject.getString("account"));
                newPile.setDelete(false);
                newPile.setPassword(jsonObject.getString("password"));
                newPile.setRegTime(TimeFormatter.toTimeYear());
                newPile.setPileNO(pileNo);
                newPile.setState(Pile.STATE_NOREGISTER);
                newPile.setOperatorNO("1234567");
                newPile.setStationNO(stationNo);
                newPile.setSn("0000000000000000");
                newPile.setOwnType(Pile.OWN_TYPE_PRIV);// 表示个人电桩
                newPile.setTel(AppUser.getPrincipal().toString());
                newPile.setSoftVersion("0121");
                newPile.setFstLevType("01");
                newPile.setScdLevType("01");
                newPile.setPhyType(Pile.PHY_TYPE_AC);
                station.setStationNO(stationNo);

                station.setAddress("未知，请联系分享用户");
                if (jsonObject.has("province"))
                    station.setProvince(jsonObject.getString("province"));
                if (jsonObject.has("city"))
                    station.setCity(jsonObject.getString("city"));
                if (jsonObject.has("county"))
                    station.setCounty(jsonObject.getString("county"));
                if (jsonObject.has("street"))
                    station.setStreet(jsonObject.getString("street"));
                if (jsonObject.has("province") && jsonObject.has("city") && jsonObject.has("county")
                        && jsonObject.has("street"))
                    station.setAddress(jsonObject.getString("province") + "省" + jsonObject.has("city")
                            + jsonObject.has("county") + jsonObject.has("street"));

                station.setStationNO(stationNo);
                station.setName(userNo + "站");
                station.setDelete(false);
                station.setOperatorNO("1234567");
                station.setMgrName(userNo);
                station.setRegTime(TimeFormatter.toTimeYear());
                station.setState(Station.USING);


            } else {
                result.put("added", false);
                result.put("errcode", ERR_DEVICE);
                result.put("message", "电桩地址有误");
                return result;
            }

        } catch (org.json.JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (pileRegister.selPile(newPile.getPileNO()) != null) {
            result.put("added", false);
            result.put("errcode", ERR_DEVICE);
            result.put("message", "设备地址已注册");
            return result;
        }
        int i = 0;
        int j = 0;
        if (newPile != null) {
            i = pileRegister.addPileManually(newPile);
            j = stationmanager.addStation(station);
        }
        if (i <= 0 || j <= 0) {
            result.put("added", false);
            result.put("errcode", FAILURE);
            result.put("message", "设备注册失败");
        } else {
            result.put("added", true);
            result.put("errcode", SUCCESS);
            result.put("message", "设备注册成功");
        }
        return result;
    }

    @RequestMapping(value = "/sharestation", method = RequestMethod.GET)
    @ResponseBody
    public Object selSharePile() {
        JSONObject jsonObject = new JSONObject();
        List<Pile> chargePiles_time = null;
        Subject subject = SecurityUtils.getSubject();
        String tel = subject.getPrincipal().toString();
        jsonObject.put("success", true);
        if (tel == null) {
            jsonObject.put("added", false);
            jsonObject.put("errcode", ERR_DATA);
            jsonObject.put("message", "桩数据有误");
            return jsonObject;
        }

        List<Pile> piles = pileRegister.selPileByTel(tel);
        if (piles != null) {
            chargePiles_time = new ArrayList<>();
            for (Iterator<Pile> iterator = piles.iterator(); iterator.hasNext(); ) {
                Pile chargePile = iterator.next();
                chargePile.setRegTime(TimeFormatter.getTime(chargePile.getRegTime()));
                chargePile.setLogoutTime(TimeFormatter.getTime(chargePile.getLogoutTime()));
                chargePiles_time.add(chargePile);
            }
            jsonObject.put("data", chargePiles_time);

        } else {
            jsonObject.put("data", "");
        }
        return jsonObject;
    }

    /**
     * 实现电桩编号的校验
     *
     * @param pileNo
     * @return
     */
    public boolean checkPileNo(String pileNo) {

        return true;

    }
}
